package com.example.security.handler;

import io.micrometer.common.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class JwtAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    @Qualifier("userDetailsServiceImpl")//需要指定注入的是那个类，避免报错。
    private UserDetailsService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) {
        String username = String.valueOf(authentication.getPrincipal());
        String password = String.valueOf(authentication.getCredentials());
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        System.out.println("------------->       JwtAuthenticationProvider:"+userDetails.getUsername()+","+userDetails.getPassword());
        if(userDetails != null && StringUtils.isNotBlank(userDetails.getPassword())
                && userDetails.getPassword().equals(password)){
            return new UsernamePasswordAuthenticationToken(username,password,authentication.getAuthorities());
        }
        try {
            throw new Exception("RespCodeEnum.NAME_OR_PASSWORD_ERROR");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return UsernamePasswordAuthenticationToken.class.equals(authentication);
    }
}
